package com.etlmaster.datax.plugins.tranformer;

import java.util.Map;

import com.dp.nebula.wormhole.common.interfaces.ILine;
import com.dp.nebula.wormhole.common.interfaces.IParam;
import com.etlmaster.executor.utils.JsonHelper;
import com.etlmaster.executor.utils.LogWriter;

/**
 * 行级处理 编码转换
 * @author wugf
 * @date 2016-04-29
 */
@ComponentAnnotation("codeMap")
public class TransFieldByCodeMap extends LineTransProcessor{

	private Map codeMap;
	private String codeMapName;
	private String insertType;
	private String nonExistPolocy;
	private String constantValue;
	public TransFieldByCodeMap(Integer fieldIndex, String changeCode,String paramStr,IParam param) {
		super(fieldIndex, changeCode,paramStr,param);
		this.codeMap=(Map) JsonHelper.getInstance().read(this.getParam().getValue(codeMapName));
	}

	@Override
	public void transField(ILine line,IParam param) {
		String sourceValue=line.getField(this.getFieldIndex());
		if(codeMap.containsKey(sourceValue)){
			changeCode(line,(String) codeMap.get(sourceValue));
		}else{
			changeNonExistCode(line);
		}
	}
	
	public void changeCode(ILine line,String targetValue){
		String insertType=this.getParam().getValue(this.insertType,"replace");
		if(insertType.equals("replace")){
			line.replaceField(targetValue, this.getFieldIndex());
		}else{
			line.addField(targetValue);
		}
	}
	public void changeNonExistCode(ILine line){
		if(nonExistPolocy.equals("constant")){
			changeCode(line,this.getParam().getValue(this.constantValue,"none"));
		}else if(nonExistPolocy.equals("delete")){
			line.setSkip(true);
		}else{
			LogWriter.addLog("WARN","不支持的转换类型:{}",nonExistPolocy);
		}
	}

	@Override
	public boolean isSkip() {
		
		return false;
	}

}
